package com.yao.ui

import android.app.Activity
import android.arch.lifecycle.LifecycleOwner
import android.content.Context
import android.content.Intent
import android.database.ContentObserver
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.base.glide.ArcReflectedTransformation
import com.base.mvp.BaseMvpActivity
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.entity.MultiItemEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.lib.updater.DownloadContentObserver
import com.yao.AppConfig
import com.yao.R
import com.yao.adapter.IndexAdapter
import com.yao.helper.DialogFragmentHelper
import com.yao.image.GlideUtil
import com.yao.presenter.IndexContract
import com.yao.presenter.IndexPresenter
import com.yao.presenter.bean.AppBean
import com.yao.presenter.bean.BannerBean
import com.yao.presenter.bean.IndexDataBean
import com.yao.ui.fragment.IndexSearchFragment
import com.yao.ui.fragment.UpdateDialogFragment
import com.yao.util.AlertUtil
import com.yao.util.PreferenceCache
import com.yao.widget.PsdGestureView.STATE_REGISTER
import kotlinx.android.synthetic.main.activity_index.*

class IndexActivity : BaseMvpActivity<IndexPresenter>(), IndexContract.View {
    private var banners: Array<String> = arrayOf(
        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1564396852644&di=4ab24fcef53d37ca7b6e16ec6b6f6a9b&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201409%2F19%2F20140919033302_FrnUy.jpeg",
        "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543899454775&di=f6b657adc35d3614c474eeec42bb0dae&imgtype=0&" + "src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01d4c959afa1f9a8012028a9fd5f9a.jpg%401280w_1l_2o_100sh.jpg"
    )

    private var mAdapter: IndexAdapter? = null

    private var contentObserver: ContentObserver? = null

    companion object {
        @JvmStatic
        fun startActivity(mContext: Context) {
            val intent = Intent(mContext, IndexActivity::class.java)
            mContext.startActivity(intent)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_index
    }

    override fun bindViewToPresenter(): IndexPresenter {
        return IndexPresenter()
    }

    override fun useDynamicTitleBar(): Boolean {
        return false
    }

    override fun initView(p0: Bundle?) {
        mPresenter.attachView(this)

        val packInfo = packageManager.getPackageInfo(packageName, 0)
        val version = packInfo.versionName
        mPresenter.getData(version, Build.VERSION.RELEASE)


        index_appbar?.setPadding(0, statusBarHeight, 0, 0)

        index_bannerview?.setAdapter({ _, list, position ->
            val imageView = ImageView(mContext)
            val requestOptions = RequestOptions()
            requestOptions.transforms(ArcReflectedTransformation(100))
            GlideUtil.loadImage(imageView, list[position], requestOptions)
            imageView
        }, banners.toList())

        mAdapter = IndexAdapter()
        val mLayoutManager = GridLayoutManager(this, 4, RecyclerView.VERTICAL, false)
        index_rv?.layoutManager = mLayoutManager as RecyclerView.LayoutManager?
        index_rv?.adapter = mAdapter
        mLayoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                var result = 4
                if (mAdapter?.getItemViewType(position) == AppConfig.ItemType.ITEMTYPE_INDEX) {
                    result = 1
                }
                return result
            }
        }

        mAdapter?.setOnItemClickListener { _, _, position ->
            val indexDataBean = mAdapter?.data?.get(position)
            if (indexDataBean?.itemType == AppConfig.ItemType.ITEMTYPE_INDEX) {
                val item = indexDataBean as IndexDataBean.ChildrenBean
                YaoWebViewActivity.startActivity(mContext, item.appName, item.appLink)
            }
        }

        index_rv?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                val mLayoutManager = recyclerView.layoutManager as GridLayoutManager
                val position = mLayoutManager.findFirstCompletelyVisibleItemPosition()
                if (position < mAdapter?.data?.size!!) {
                    val item = mAdapter?.data?.get(position)
                    if (item?.itemType == AppConfig.ItemType.ITEMTYPE_INDEX_TITLE) {
                        val bean = item as IndexDataBean
                        index_tab.currentTab = bean.position
                    }
                }
            }
        })

        index_tab?.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabReselect(position: Int) {

            }

            override fun onTabSelect(position: Int) {
                mAdapter?.data?.let {
                    for (item in it) {
                        if (item.itemType == AppConfig.ItemType.ITEMTYPE_INDEX_TITLE) {
                            val bean = item as IndexDataBean
                            if (bean.position == position) {
                                val mLayoutManager = index_rv.layoutManager as GridLayoutManager
                                mLayoutManager.scrollToPositionWithOffset(bean.pos, 0)
                                break
                            }
                        }
                    }
                }
            }
        })

        et_index?.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    val str = et_index.editableText.toString()
                    if (!TextUtils.isEmpty(str)) {
                        IndexSearchFragment.show(supportFragmentManager, str)
                        et_index.setText("")
                    } else {
                        AlertUtil.t(mContext, "查询内容不能为空", Toast.LENGTH_SHORT)
                    }
                    // 当按了搜索之后关闭软键盘
                    val manager = baseContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    manager.hideSoftInputFromWindow(et_index.windowToken, 0)
                    return true
                }
                return false
            }
        })
    }

    override fun release() {
        index_rv.clearOnScrollListeners()
        index_tab.setOnTabSelectListener(null)
    }

    override fun onSuccessUpdate(data: AppBean?) {
        data?.let {
            UpdateDialogFragment.show(supportFragmentManager, data.apkVersion, data.updateContent, data.fileUrl)
        }
    }

    override fun onSuccess(result: MutableList<IndexDataBean>?) {
        val data = ArrayList<MultiItemEntity>()
        val titles = ArrayList<String>()
        result?.let {
            for (indexDataBean in it) {
                val bean = IndexDataBean()
                bean.position = titles.size
                bean.pos = data.size
                bean.classifyName = indexDataBean.classifyName
                bean.classifyId = indexDataBean.classifyId
                titles.add(bean.classifyName)
                data.add(bean)
                data.addAll(indexDataBean.children)
            }
        }
        val footer = MultiItemEntity { AppConfig.ItemType.ITEMTYPE_BOTTOM }
        data.add(footer)
        index_tab.setTitles(titles.toTypedArray())
        mAdapter?.setNewData(data)
    }

    override fun onSuccessBanner(data: MutableList<BannerBean>?) {
        val banners = ArrayList<String>()
        data?.let {
            for (banner in data) {
                if (banner.pic.isNullOrEmpty()) {
                    continue
                }
                banners.add(banner.pic)
            }
        }
        //TODO
        banners.isNotEmpty().let {
            index_bannerview?.setAdapter({ _, list, position ->
                val imageView = ImageView(mContext)
                val requestOptions = RequestOptions()
                requestOptions.transforms(ArcReflectedTransformation(150))
                requestOptions.placeholder(R.drawable.shape_placeholder_2).error(R.drawable.shape_placeholder_2)
                GlideUtil.loadImage(imageView, list[position], requestOptions)
                imageView
            }, banners)
        }
    }

    override fun showLoading() {
        DialogFragmentHelper.showLoadingDialog(supportFragmentManager)
    }

    override fun onFail(code: Int, msg: String?) {
        AlertUtil.t(this, msg, Toast.LENGTH_SHORT)
        if (code == 401) {
            PreferenceCache.putToken("")
            PreferenceCache.putAutoLogin(false)

            val sp = mContext.getSharedPreferences("STATE_DATA", Activity.MODE_PRIVATE)
            val edit = sp.edit()
            edit.putInt("state", STATE_REGISTER)
            edit.commit()

            LoginActivity.startActivity(this)
            finish()
        }
    }

    override fun bindLifecycleOwner(): LifecycleOwner {
        return this@IndexActivity
    }

    override fun hideLoading() {
        DialogFragmentHelper.closeLoadingDialog(supportFragmentManager)
    }

    override fun onError(p0: Throwable?) {

    }

}